package org.course.weather.util;

import jakarta.servlet.http.HttpServletRequest;
import org.course.weather.entity.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class MyExceptionHandler {
    final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public JsonResult<Object> handle_MyException(HttpServletRequest req, MyException e){
        String req_path = "";
        if (req != null) {
            req_path = req.getRequestURI();
        }
        logger.error("接口[{}]出现自定义异常, {}", req_path, e.getErrorMsg());
        return new JsonResult<>(e.getErrorCode(),e.getErrorMsg());
    }

    /**
     * 处理参数校验异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class})
    @ResponseBody
    public JsonResult<Object> handle_BindException(HttpServletRequest req, Exception e, BindingResult bindingResult){
        String req_path = "";
        if (req != null) {
            req_path = req.getRequestURI();
        }
        if (bindingResult.hasErrors()) {
            String messages = bindingResult.getAllErrors()
                    .stream()
                    .map(ObjectError::getDefaultMessage)
                    .reduce((m1, m2) -> m1 + " & " + m2)
                    .orElse("参数输入有误");
            logger.error("接口[{}]出现参数绑定异常, {}", req_path, messages);
        }
        logger.error("接口[{}]出现请求参数异常, {}", req_path, e.getMessage());
        return new JsonResult<>("-1","请求参数异常");
    }

    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonResult<Object> handle_Exception(HttpServletRequest req, Exception e){
        String req_path = "";
        if (req != null) {
            req_path = req.getRequestURI();
        }
        logger.error("接口[{}]出现系统异常, {}", req_path, e.getMessage());
        return new JsonResult<>("-1","系统异常");
    }
}
